package pe.gob.sunat.framework.spring.web.view;

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.view.AbstractView;

import pe.gob.sunat.framework.spring.web.util.JsonUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Devuelve en el request los datos recibidos por parametro,
 * a una cadena de formato JSON.
 * @author Carlos Enrique Quispe Salazar
 * @since 17/10/2007
 * @version 1.0
 */
public class IFrameJsonView extends AbstractView {
	protected final Log log = LogFactory.getLog(getClass());
	
	@SuppressWarnings("unchecked")
	protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		boolean isArray = false;
		Object model = null;
		
		log.debug("Convirtiendo a JSON el Bean: " + this.getBeanName());
		model = map.get("datamodel");
//		log.debug("Parametro: " + model.toString());
		
		JSONObject jsonObject = null;
		JSONArray  jsonArray =  null;
		
		if(model != null) {
			if(model instanceof List) {
				isArray = true;
				jsonArray = JSONArray.fromObject(model, JsonUtil.getJsonNoNull());   
			}
			else {
				jsonObject = JSONObject.fromObject(model, JsonUtil.getJsonNoNull());   
			}
		}
		else {
			jsonObject = JSONObject.fromObject(map, JsonUtil.getJsonNoNull());   
		}

		this.setContentType("text/html");	
		response.setContentType(this.getContentType());
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setHeader("Cache-Control", "private");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head></head>");
		out.println("<body>");
		out.print("<textarea style='width: 100%; height: 100px;'>");
		
		if(isArray) {
			out.print(jsonArray.toString());
			log.debug("Devolviendo arreglo : JSON=" + jsonArray.toString());
		}
		else {
			out.print(jsonObject.toString());
			log.debug("Devolviendo objeto : JSON=" + jsonObject.toString());
		}
		out.println("</textarea>");
		out.println("</body>");
		out.println("</html>");
		out.close();
	}
}
